import {
  defineStore
} from 'pinia'
import {
  ref,
  reactive,
  computed
} from 'vue'
import {
  getMusicPlayerAPI
} from '@/common/api/musicAPI.js'
import {
  getPlaylistDetailAPI,
  getPlaylistAllDataAPI
} from '@/common/api/songListAPI.js'

export const useMusicStore = defineStore('music', () => {
  // 播放器数据
  const playMusic = ref(null)
  const musicInfo = ref(null)
  // 播放与暂停
  const isPlay = ref(false)
  // 音乐播放的时间点
  const currentTime = ref(0)
  // 当前音频的长度
  const duration = ref(0)

  // 当前音频播放与总长度百分比
  const currentTimePercentum = computed(() => {
    return (currentTime.value / duration.value) * 100
  })

  // 获取歌单详情
  const playlistDetail = ref({})
  const getPlaylistDetail = async (id) => {
    const res = await getPlaylistDetailAPI(id)
    if (res.code !== 200) return uni.showToast({
      title: '获取歌单详情失败！',
      duration: 2000,
      icon: 'error'
    })
    playlistDetail.value = res.playlist
  }

  // 选中歌单全部歌曲
  const playlistAllData = ref([])
  // 获取歌单全部歌曲
  const getPlaylistAllData = async (id, limit, offset) => {
    if(offset === 0){
      playlistAllData.value = []
    }
    console.log(offset);
    const res = await getPlaylistAllDataAPI(id, limit, offset)
    if (res.code !== 200) return uni.showToast({
      title: '获取歌单歌曲失败！',
      duration: 2000,
      icon: 'error'
    })
    playlistAllData.value.push(...res.songs)
  }

  // 获取音乐
  const getMusicPlayer = async (id, level) => {
    const res = await getMusicPlayerAPI(id, level)
    if (res.code !== 200) return uni.showToast({
      title: '获取音乐失败！',
      duration: 2000,
      icon: 'error'
    })
    playMusic.value = res.data[0]
    duration.value = (res.data[0].time / 1000)
  }

  // 播放下一首
  const nextSong = () => {
    isPlay.value = false
    playlistAllData.value.forEach((item, index) => {
      if (item.id === playMusic.value.id) {
        let i = index + 1
        if (i > playlistAllData.value.length - 1) {
          i = 0
        }
        currentTime.value = 0
        musicInfo.value = playlistAllData.value[i]
        getMusicPlayer(playlistAllData.value[i].id).then(() => {
          isPlay.value = true
        })
      }
    })

  }

  // 播放上一首
  const previousSong = () => {
    isPlay.value = false
    playlistAllData.value.forEach((item, index) => {
      if (item.id === playMusic.value.id) {
        let i = index - 1
        if (i < 0) {
          i = playlistAllData.value[playlistAllData.value.length - 1]
        }
        currentTime.value = 0
        musicInfo.value = playlistAllData.value[i]
        getMusicPlayer(playlistAllData.value[i].id).then(() => {
          isPlay.value = true
        })
      }
    })
  }

  return {
    playMusic,
    musicInfo,
    isPlay,
    currentTime,
    duration,
    currentTimePercentum,
    playlistAllData,
    playlistDetail,
    getPlaylistDetail,
    getPlaylistAllData,
    getMusicPlayer,
    nextSong,
    previousSong
  }
})